﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyBBS.Data.Utility
{
    public interface IPagedList
    {
        int TotalCount
        {
            get;
            set;
        }

        int? PageIndex
        {
            get;
            set;
        }

        int PageSize
        {
            get;
            set;
        }

        bool IsPreviousPage
        {
            get;
        }

        bool IsNextPage
        {
            get;
        }
    }

    public class PagedList<T> : List<T>, IPagedList
    {
        #region IPagedList Members

        public int TotalCount
        {
            get;
            set;

        }

        public int? PageIndex
        {
            get;
            set;
        }

        public int PageSize
        {
            get;
            set;
        }

        public bool IsPreviousPage
        {
            get {
                return (PageIndex ?? 0) > 0;
            }
        }

        public bool IsNextPage
        {
            get {
                return (((PageIndex??0) + 1) * this.PageSize) < TotalCount;
            }
        }

        #endregion

        public PagedList(IQueryable<T> query, int? index, int pageSize)
        {
            this.TotalCount = query.Count();
            this.PageIndex = index;
            this.PageSize = pageSize;

            this.AddRange(query.Skip((index ?? 0) * pageSize).Take(pageSize).ToList());
        }
    }

    public static class Pagination
    {
        public static PagedList<T> ToPagedList<T>(this IQueryable<T> source, int? index, int pageSize)
        {
            return new PagedList<T>(source, index, pageSize);
        }

        public static PagedList<T> ToPagedList<T>(this IQueryable<T> source, int? index)
        {
            return new PagedList<T>(source, index, 10);
        }
    }
}
